import SockJS from "sockjs-client";
import Stomp from "stompjs";


let stompClient = null;
let username = null;
let messageInput = null;
let receivedData = null;
//  建立ws连接
function connect(event) {
  const websocket = new SockJS("http://192.168.16.140:30805/pv/websocket/ws", [], { transports: "websocket" });
  console.log('websocket')
  console.log(websocket)
  stompClient = Stomp.over(websocket);
  console.log('stompClient:')
  console.log(stompClient)
  stompClient.connect({ username: '9999999' }, onConnected, onError);


}

// 连接上ws之后
function onConnected() {

  if (username) {
    console.log('sender------------')
    // 点对点
    var url = "/user/" + username + "/topic/one";
    stompClient.subscribe(url, onMessageReceived);
    sendAllMessage()
  } else {
    // 多对多
    stompClient.subscribe("/topic/public", onMessageReceived);
  }
}

// ws连接报错

function onError(error) {
  console.log("ws连接报错", error);
}

// 发送消息
function sendAllMessage(event) {
  if (stompClient) {
    console.log('username:',username)
    var chatMessage = {
      sender: username,
      content: messageInput,
      receiver: "222",
      type: "XT_ELECTRIC_MONITOR_INFO",
    };

    console.log('sendAllMessage------------')

    stompClient.send(
      "/application/pv.addUser",
      {},
      JSON.stringify(chatMessage)
    );
    // stompClient.send("/usr/pv.sendOneMessage", {}, JSON.stringify(chatMessage));
  }
}
// 收到ws消息

function onMessageReceived(payload) {
  receivedData = JSON.parse(payload.body);
  console.log("ws消息", receivedData);
  if (window && window.wsCallback) {
    window.wsCallback(receivedData);
  }
}

// 断掉ws连接
function disconnect() {
  if (stompClient) {
    stompClient.disconnect();
  }
}

const WS = {
  connect: () => {
    connect();
  },
  disconnect: () => {
    disconnect();
  },
  changeData: (data) => {
    let { user, message } = data;
    username = 'corp_' + user;
    messageInput = message;
  },
};

export default WS;
